package com.twu.biblioteca.data;

import com.twu.biblioteca.exceptions.BookAlreadyCheckedOutException;
import com.twu.biblioteca.exceptions.BookNotCheckedOutException;

import java.util.*;

/**
 * Created by florian on 27/12/13.
 */
public class BookDAO {

    private final Map<Integer, Book> idToBookMap;

    public BookDAO() {
        Collection<Book> dummyBooks = Arrays.asList(
                new Book(0, "Test Driven Development: By Example", "Kent Beck", true),
                new Book(1, "Effective Java", "Joshua Bloch", true),
                new Book(2, "Pragmatic Programmer", "Andrew Hunt", true),
                new Book(9, "Clean Code", "Robert C. Martin", false));
        this.idToBookMap = new HashMap<Integer,Book>(dummyBooks.size());
        for (Book book : dummyBooks) {
            idToBookMap.put(book.getId(),book);
        }
    }

    public Collection<Book> getAllAvailableBooks() {
        Collection<Book> availableBooks = new ArrayList<Book>(idToBookMap.size());
        for (Book book : idToBookMap.values()) {
            if (book.isAvailable()) {
                availableBooks.add(book);
            }
        }
        return availableBooks;
    }

     /**
     * Finds the book with the indicated id or null in case no book with this id exists
     * @param id
     * @return the book or null
     */
    public Book findBookForId(int id) {
        return idToBookMap.get(id);
    }

    public void checkoutBook(Book bookToCheckout) throws BookAlreadyCheckedOutException {
        if (!bookToCheckout.isAvailable()) {
            throw new BookAlreadyCheckedOutException();
        }
        bookToCheckout.setAvailable(false);
    }

    public void returnBook(Book bookToReturn) throws BookNotCheckedOutException {
        if (bookToReturn.isAvailable()) {
            throw new BookNotCheckedOutException();
        }
        bookToReturn.setAvailable(true);

    }
}
